package cn.topcodes.tcsf.cms.web.controller;

import cn.topcode.unicorn.utils.ValidationUtil;
import cn.topcodes.tcsf.admin.commons.api.controller.admin.AdminController;
import cn.topcodes.tcsf.admin.commons.api.domain.ApiResponseEntity;
import cn.topcodes.tcsf.cms.domain.entity.ArticleCatalog;
import cn.topcodes.tcsf.cms.domain.entity.ProductionCatalog;
import cn.topcodes.tcsf.cms.domain.form.ArticleCatalogForm;
import cn.topcodes.tcsf.cms.domain.form.ProductionCatalogForm;
import cn.topcodes.tcsf.cms.domain.vo.NestableSort;
import cn.topcodes.tcsf.cms.domain.vo.ProductionCatalogVo;
import cn.topcodes.tcsf.cms.service.ProductionCatalogService;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * ProductionCatalog管理控制器
 *
 * @author Yvan
 * @date 2018-02-09 10:46:47
 */
@Controller
@RequestMapping("/admin/cms/production_catalog")
public class ProductionCatalogController extends AdminController<ProductionCatalog, ProductionCatalogVo, ProductionCatalogForm> {

    @Autowired
    private ProductionCatalogService productionCatalogService;

    @Override
    protected String getPageFolder() {
        return "/cms/production_catalog";
    }

    @RequestMapping("save-sort")
    @ResponseBody
    public ApiResponseEntity saveSort(@RequestBody(required = true) List<NestableSort> sort) {

        productionCatalogService.saveSort(sort);
        return ApiResponseEntity.buildOK();
    }

    @Override
    public ApiResponseEntity create(HttpServletRequest request,
                                    @Valid @ApiParam("创建资源表单") ProductionCatalogForm form, BindingResult result) {
        ValidationUtil.validate(result);
        ProductionCatalog entity = this.form2Entity(form);
        entity.setSort(0);
        Long id = productionCatalogService.create(entity);
        return ApiResponseEntity.buildOK().setBody(id);
    }

    @Override
    public ApiResponseEntity<Void> update(HttpServletRequest request, @Valid @ApiParam("更新资源表单") ProductionCatalogForm form, BindingResult result) {

        ProductionCatalog t = this.form2Entity(form);
        ProductionCatalog articleCatalog = productionCatalogService.findOne(form.getId());
        t.setSort(articleCatalog.getSort());
        t.setParentId(articleCatalog.getParentId());
        productionCatalogService.update(t);
        return ApiResponseEntity.buildOK();
    }
}
